package com.snailct.bpp.service.core.commons.support;

import com.snailct.bpp.commons.utils.ReflectUtil;
import com.snailct.bpp.service.core.definition.ServiceDefinition;
import com.snailct.bpp.service.core.definition.ServiceMeta;
import com.snailct.bpp.service.core.utils.XmlUtil;
import org.apache.commons.lang.StringUtils;


import java.util.List;
import java.util.Map;

/**
 * Created by huangxa on 2016/7/18.
 */
public class ParamMapUtils {
    public static Object[] mapServiceParam(ServiceDefinition serviceDefinition){
        Map<String,String> params = XmlUtil.getReqParams(serviceDefinition.getSendBody());
        List<ServiceMeta> paramTypes = serviceDefinition.getServiceMetas();
        Object[] args = new Object[paramTypes.size()];
        int i=0;
        for(ServiceMeta paramType : paramTypes){
            try {
                if(paramType==null || StringUtils.isEmpty(paramType.getParamType())) continue;
                try {
                    if("java.lang.Integer".equals(paramType.getParamType())){
                        //设置值
                        for (Map.Entry<String, String> entry : params.entrySet()) {
                            args[i] = new Integer(entry.getValue());
                        }
                    }else{
                        Class<?> paramClazz =  Class.forName(paramType.getParamType());
                        args[i]=(Object)paramClazz.newInstance();
                        //设置值
                        for (Map.Entry<String, String> entry : params.entrySet()) {
                            if(!ReflectUtil.setMethodValue(args[i],entry.getKey(),entry.getValue())){
                                throw new RuntimeException("setter param type error");
                            }
                        }
                    }

                    i++;
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }

            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        return args;
    }
}
